package com.jz.netthings.engine.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jy.faceValidate.utils.FaceValidateBase;
import com.jy.faceValidate.utils.FaceValidateUtils;
import com.jz.netthings.appengine.baseData.AllotData;
import com.jz.netthings.appengine.baseData.MachineData;
import com.jz.netthings.appengine.baseData.ProviderData;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.queue.ChairMgr;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.queue.ProviderQueue;
import com.jz.netthings.appengine.support.BeanSupport;
import com.jz.netthings.appengine.support.SendMsgSupport;
import com.jz.netthings.application.providerCreate.bean.ProviderZw;
import com.jz.netthings.application.providerCreate.service.ProviderInfoService;
import com.jz.netthings.application.upload.service.UploadService;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.engine.bean.*;
import com.jz.netthings.engine.service.ClientService;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.netty.protocol.bean.ZxdcMsgPacket;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import com.jz.netthings.support.SimpleCoreResponse;
import com.jz.netthings.system.service.JyUserService;
import com.jz.netthings.system.utils.AdscmSystemUtils;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 客戶端基本Controller
 */
@RestController
@RequestMapping("/netthings/engine/base")
public class ClientBaseController {

//    private static FaceValidateBase f = FaceValidateUtils.faceV;//主要就是预加载人脸识别模块

    @Autowired
    ProviderQueue providerQueue;

    @Autowired
    ClientService  clientService;
    @Autowired
    ProviderInfoService providerInfoService;
    @Autowired
    JyUserService jyUserService;

    @Autowired
    UploadService uploadService;

    /**
     *  上传信息进行建档流程
     * @param
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/providerCreate")
    public SimpleCoreResponse providerCreate(@RequestBody BloodUser bloodUser) throws AdscmSystemException {
             BloodUser result   = clientService.providerCreate(bloodUser);
        return new SimpleCoreResponse("200", "建档成功", result);
    }
    /**
     * 上传建档照片
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/saveProviderCreatePhoto")
    public SimpleCoreResponse saveProviderCreatePhoto(@RequestBody BloodUser bloodUser) throws AdscmSystemException {
        boolean result   = clientService.saveProviderCreatePhoto(bloodUser);
        return new SimpleCoreResponse("200", "上传成功", result);
    }

    /**
     * 上传指纹信息
     * @param fingerprint
     * @param cardId
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/saveProviderCreateZw/{cardId}")
    public SimpleCoreResponse saveProviderCreateZw(@RequestBody List<Fingerprint> fingerprint,@PathVariable String cardId) throws AdscmSystemException {
        boolean result   = clientService.saveProviderCreateZw(fingerprint,cardId);
        return new SimpleCoreResponse("200", "上传成功", result);
    }

    /**
     * 根据卡号获取指纹
     * @param cardId
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/getProviderCreateZw/{cardId}")
    public SimpleCoreResponse getProviderCreateZw(@PathVariable String cardId) throws AdscmSystemException {
            List<Fingerprint>  result= clientService.getProviderCreateZw(cardId);
        return new SimpleCoreResponse("200", "上传成功", result);
    }


    /**
     * 客户端浆员登记：查询浆员基本信息接口，同时判断浆员是否有献浆的条件
     *   1. 判断身份证是否到期
     2. 判断年龄是否超龄
     3. 判断是否永拒
     4. 对于已经登记的，直接返回登记信息。
     5. 判断距离上次献浆是否间隔了配置的期限。
     * @param idCard
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/providerReqRegisterMsg/{idCard}")
    public SimpleCoreResponse providerReqRegisterMsg(@PathVariable("idCard") String idCard) throws AdscmSystemException {
        System.out.println("查询登记浆员信息："+idCard);
        BloodUser user  = clientService.providerReqRegisterMsg(idCard);
        return new SimpleCoreResponse("200", "查询成功", user);
    }

    @RequestMapping("/providerRegister")
    public SimpleCoreResponse providerRegister(@RequestBody RegisterReqData registerReqData) throws AdscmSystemException {
        RegisterData result   = clientService.providerRegister(registerReqData);
        return new SimpleCoreResponse("200", "登记成功", result);
    }


    /**
     * 查询不同状态的浆员的环节数据
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/providerList")
    public SimpleCoreResponse providerList(@RequestParam("statusList") String statusList) throws AdscmSystemException {

        JSONArray json = JSONArray.parseArray(statusList);

        return new SimpleCoreResponse("200", "查询成功", providerQueue.getProviderListByStatus(json.toJavaList(Integer.class)));
    }
    /**
     * 根据指令查询不同状态的浆员的环节数据
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/providerListByCmd/{doCmd}")
    public SimpleCoreResponse providerListByCmd(@PathVariable("doCmd") String doCmd) throws AdscmSystemException {


        return new SimpleCoreResponse("200", "查询成功", providerQueue.getProviderListByCmd(doCmd));
    }

    private static int temp = 1;
    /**
     * 获取机器集合
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/machineList")
    public SimpleCoreResponse machineList() throws AdscmSystemException {

        return new SimpleCoreResponse("200", "查询成功", MachineMgr.getInstance().getMachineQueue());
    }

    /**
     * 查询护士头像
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/nursePhoto/{code}")
    public SimpleCoreResponse nursePhoto(@PathVariable("code") String code) throws AdscmSystemException {

        JyUser jyUser = jyUserService.selectById(code);

        String userPhoto = jyUser.getPhoto();
        byte[] photo = null;
        if (AdscmBaseUtils.getInstance().isNotEmpty(userPhoto,null)){
//            photo = AdscmSystemUtils.getInstance().getFileBytes(userPhoto);
            photo = uploadService.downloadImageReturnBytes(userPhoto);
        }else {
            photo = AdscmBaseUtils.getInstance().getNullNursePhoto();
        }
        if (photo == null){
            photo = AdscmBaseUtils.getInstance().getNullNursePhoto();
        }
        photo = AdscmBaseUtils.getInstance().buildIcon(photo, 100, 100);

        return new SimpleCoreResponse("200", "查询成功", photo);
    }
    /**
     * 验证管理员
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/validateAdmin/{code}/{pwd}")
    public SimpleCoreResponse validateAdmin(@PathVariable("code") String code,@PathVariable("pwd") String pwd) throws AdscmSystemException {

        return new SimpleCoreResponse("200", "验证成功", code);
    }

    @RequestMapping("/sendProviderAllot11")
    public SimpleCoreResponse sendProviderAllot11() throws AdscmSystemException {

        ChannelHandlerContext macCtx = MachineMgr.getInstance().getMacCtx("008");
        MachineData machine = MachineMgr.getInstance().getMachine("008");

        ZxdcMsgPacket machine_status_changed = new ZxdcMsgPacket();
        machine_status_changed.setCmd("machine_status_changed");
        machine_status_changed.setHasResponse(false);
        machine_status_changed.setLevel(3);
        HashMap<String, Object> values = new HashMap<String, Object>();
        values.put("mcode", machine.getCode());
        values.put("info", JSON.toJSONString(machine, SerializerFeature.PrettyFormat));
        machine_status_changed.setValues(values);
        System.out.println("^^^^^^^^^^^"+machine_status_changed);
        NettyMsgHelper.sendPacket(macCtx,machine_status_changed);


        return new SimpleCoreResponse("200", "成功", machine_status_changed);
    }

    @RequestMapping("/sendProviderAllot")
    public SimpleCoreResponse sendProviderAllot() throws AdscmSystemException {

        ChannelHandlerContext macCtx = MachineMgr.getInstance().getMacCtx("005");
        MachineData machine = MachineMgr.getInstance().getMachine("005");


        ZxdcMsgPacket alloc_donor = new ZxdcMsgPacket();
        alloc_donor.setCmd("alloc_donor");
        alloc_donor.setTimeout(20000);
        alloc_donor.setHasResponse(true);
        alloc_donor.setLevel(1);
        HashMap<String, Object> values1 = new HashMap<String, Object>();
        values1.put("regCode","201903260001");
        values1.put("donor_no", "402899");
        values1.put("donor_name", "杨云云");
        values1.put("age", 18);
        values1.put("sex", "男");
        values1.put("address", "四川省成都市武侯区");
        byte[] photo = AdscmBaseUtils.getInstance().buildIcon(AdscmSystemUtils.getInstance().getFileBytes("D:\\adscm\\images\\12.jpg"), 240, 240);
        values1.put("photo", Base64.getEncoder().encodeToString(photo));
        values1.put("donating_age", "1");//浆龄
        values1.put("last_donating_time", "2019-09-09");//上一次献浆时间
        values1.put("complains_record", "");//投诉记录
        values1.put("vessel_type", "");//血管类型
        values1.put("times", "5");//每年献浆次数
            values1.put("mCode",machine.getCode());
        alloc_donor.setValues(values1);

        List<HashMap<String, Object>> tList = new ArrayList<HashMap<String, Object>>();
        alloc_donor.setTaskList(tList);

        System.out.println("^^^^^^^^^^^"+alloc_donor);
        NettyMsgHelper.sendPacket(macCtx,alloc_donor);



        return new SimpleCoreResponse("200", "成功", alloc_donor);
    }

    /**
     * 重置设备为空闲状态
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/doFreeMachine/{mcode}")
    public SimpleCoreResponse doFreeMachine(@PathVariable("mcode") String mcode) throws AdscmSystemException {
        clientService.doFreeMachine(mcode);
        return new SimpleCoreResponse("200", "重置成功", null);
    }
    /**
     * 取消设备分配的浆员
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/freeMachineByProvider/{code}")
    public SimpleCoreResponse freeMachineByProvider(@PathVariable("code") String code) throws AdscmSystemException {
        clientService.freeMachineByProvider(code);
        return new SimpleCoreResponse("200", "取消成功", null);
    }
    /**
     * 分配的浆员（测试用）
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/allotProvider")
    public SimpleCoreResponse allotProvider() throws AdscmSystemException {
        //在缓存中获取浆员的信息
        ProviderData provider = providerQueue.getByProviderNo("100018");
        ChannelHandlerContext macCtx = MachineMgr.getInstance().getMacCtx("005");
        MachineData machine = MachineMgr.getInstance().getMachine("005");

        ProviderInfo providerInfo = providerInfoService.selectById(provider.getProviderId());


        ZxdcMsgPacket alloc_donor = new ZxdcMsgPacket();
        alloc_donor.setCmd("alloc_donor");
        alloc_donor.setTimeout(20000);
        alloc_donor.setHasResponse(true);
        alloc_donor.setLevel(1);
        HashMap<String, Object> values = new HashMap<String, Object>();
        values.put("regCode",provider.getRegisterNo());
        values.put("donor_no", provider.getProviderNo());
        values.put("donor_name", provider.getName());
        values.put("age", providerInfo.getAge());
        values.put("sex", provider.getSex());
        values.put("address",providerInfo.getAddress());
        values.put("photo", Base64.getEncoder().encodeToString(provider.getPhoto()));
        values.put("donating_age", providerInfo.getProvideAge()+"");//浆龄
        values.put("last_donating_time", AdscmDateUtils.getNowOnlyDateFomat1(providerInfo.getLastDate()));//上一次献浆时间
        values.put("complains_record", "");//投诉记录
        values.put("vessel_type", "");//血管类型
        values.put("times", "");//每年献浆次数
        values.put("mCode",machine.getCode());
        alloc_donor.setValues(values);

        List<HashMap<String, Object>> tList = new ArrayList<HashMap<String, Object>>();
        alloc_donor.setTaskList(tList);

        boolean result = NettyMsgHelper.sendAllotPacket(macCtx, alloc_donor);
        return new SimpleCoreResponse("200", "分配成功", null);
    }
    /**
     * 手动分配浆员，根据浆员卡号
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/autoAllotByProvider/{code}/{nurseid}")
    public SimpleCoreResponse autoAllotByProvider(@PathVariable("code") String code,@PathVariable("nurseid") String nurseid) throws AdscmSystemException {
        AllotData     allotData = clientService.autoAllotByProvider(code,nurseid);
        return new SimpleCoreResponse("200", "分配成功", allotData);
    }

        /**
         * 手动分配浆员，根据浆员卡号
         * @return
         * @throws AdscmSystemException
         */
    @RequestMapping("/manualAllotByProvider/{code}/{nurseid}/{mcode}")
    public SimpleCoreResponse manualAllotByProvider(@PathVariable("code") String code,@PathVariable("nurseid") String nurseid,@PathVariable("mcode") String mcode) throws AdscmSystemException {

        AllotData     allotData  = clientService.manualAllotByProvider(code,nurseid,mcode);
        return new SimpleCoreResponse("200", "分配成功", allotData);
    }



    /**
     * 一体机客户端手动处理浆员环节：呼叫体检、体检结束 等......
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/doProcessProvider/{code}/{cmd}")
    public SimpleCoreResponse doProcessProvider(@PathVariable("code") String code,@PathVariable("cmd") String cmd) throws AdscmSystemException {

        clientService.doProcessProvider(code,cmd);

        return new SimpleCoreResponse("200", "操作成功", null);
    }

    /**
     * 生成体检记录
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/bodyCheckService")
    public SimpleCoreResponse bodyCheckProvider(@RequestBody BloodUser bloodUser) throws AdscmSystemException{
        return new SimpleCoreResponse("200","操作成功",clientService.bodycheckMsg(bloodUser));
    }

    /**
     * 生成小样化检记录
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/simpleRecode")
    public SimpleCoreResponse simpleRecode(@RequestBody BloodUser bloodUser) throws AdscmSystemException{
        return new SimpleCoreResponse("200","操作成功",clientService.samlpeInsert(bloodUser));
    }

    /**
     * 获取浆员信息（缓存中当天登记的）
     * @param code
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/getBloodUser/{code}")
    public SimpleCoreResponse getBloodUser(@PathVariable("code") String code) throws AdscmSystemException {

        BloodUser bloodUser = new BloodUser();

        if (AdscmBaseUtils.getInstance().isNotEmpty(code,null)){
            ProviderData data = new ProviderData();
            if (code.length() > 10){
                data.setIdNo(code);
            }else {
                data.setProviderNo(code);
            }
            data = providerQueue.selectProviderData(data);

            if (data.getProviderId() > 0){
                ProviderInfo providerInfo = providerInfoService.selectById(data.getProviderId());
                bloodUser.setId(data.getProviderNo());
                bloodUser.setName(data.getName());
                bloodUser.setBirthday(providerInfo.getBirthday());
                bloodUser.setAddress(providerInfo.getAddress());
                bloodUser.setIdNumber(providerInfo.getIdNo());
                bloodUser.setPhoto(data.getPhoto());
                bloodUser.setPhone(providerInfo.getPhone());
                bloodUser.setCreateDate(providerInfo.getCreateDate());
                bloodUser.setSex(data.getSex());
                bloodUser.setNeedXp(data.isNeedXp());
                bloodUser.setBodyCheckMsg(data.getNeedXpMsg());
                bloodUser.setNationality(AdscmBaseUtils.getInstance().getNation(providerInfo.getNation()));
                bloodUser.setAge(providerInfo.getAge());
                bloodUser.setValidPeriod(providerInfo.getIdCardValidDate());
            }else{
                throw new AdscmSystemException("没有查询到编号【"+code+"】对应的浆员登记信息");
            }
        }else{
            throw new AdscmSystemException("参数异常....");
        }

        return new SimpleCoreResponse("200", "查询成功", bloodUser);
    }


    /**
     * 生成血浆编码
     * @param bloodUser
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/updateHeat")
    public SimpleCoreResponse updateHeat(BloodUser bloodUser) throws  AdscmSystemException{
        return new SimpleCoreResponse("200","查询成功",clientService.updateHeat(bloodUser));
    }


    /**
     *查询浆员基本信息
     * @param idCard
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/queryProviderInfo/{idCard}")
    public SimpleCoreResponse queryProviderInfo(@PathVariable("idCard") String idCard) throws AdscmSystemException {
        System.out.println("查询浆员信息："+idCard);
        BloodUser user  = clientService.queryProviderInfo(idCard);
        return new SimpleCoreResponse("200", "查询成功", user);
    }

    /**
     * 费用发放
     * @param costInfo
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/providerCost")
    public SimpleCoreResponse providerCost(@RequestBody CostInfo costInfo) throws AdscmSystemException {
        CostInfo result   = clientService.providerCost(costInfo);
        return new SimpleCoreResponse("200", "费用发放成功", result);
    }


    /**
     * 发送消息给平板测试接口
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/sendMsgToChair/{providerId}")
    public SimpleCoreResponse sendMsgToChair(@PathVariable("providerId") String providerId) throws AdscmSystemException {


        ChannelHandlerContext chairCxt = ChairMgr.getInstance().getCtxByChair("chair005");

        ProviderInfo providerInfo = providerInfoService.selectById(providerId);
        ProviderData provider = new ProviderData();
        provider.setProviderId(Long.valueOf(providerId));
        provider = providerQueue.selectProviderData(provider);


        ZxdcMsgPacket alloc_donor = new ZxdcMsgPacket();

        alloc_donor.setCmd("auth_info");
        alloc_donor.setHasResponse(true);
        alloc_donor.setLevel(3);
        HashMap<String, Object> values = new HashMap<String, Object>();
        values.put("regCode", provider.getRegisterNo());
        values.put("sfz_id", providerInfo.getIdNo());
        values.put("donor_id", providerInfo.getCardId());
        values.put("donor_name", providerInfo.getName());
        values.put("age", providerInfo.getAge());
        values.put("sex", providerInfo.getSex());
        values.put("dz",providerInfo.getAddress());
        String photo =  Base64.getEncoder().encodeToString(provider.getPhoto());
        values.put("photo",photo);
        try {
            values.put("name",providerInfo.getName());
            values.put("gender", providerInfo.getSex());
            if (providerInfo.getBirthday() != null) {
                Calendar d = Calendar.getInstance();
                d.setTime(providerInfo.getBirthday());
                int year = d.get(Calendar.YEAR);
                int month = d.get(Calendar.MONTH);
                int day = d.get(Calendar.DAY_OF_MONTH);

                values.put("year", Integer.toString(year));
                values.put("month", Integer.toString(month + 1));
                values.put("day", Integer.toString(day));
            }

            values.put("nationality", "");
            values.put("address",providerInfo.getAddress());

            values.put("face", photo);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        alloc_donor.setValues(values);

        NettyMsgHelper.sendPacketToChair(chairCxt,alloc_donor);
        return new SimpleCoreResponse("200", "分配成功", null);
    }


    /**
     * 发送加压消息给平板测试接口
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/jiayaToChair/{type}")
    public SimpleCoreResponse jiayaToChair(@PathVariable("type") String type) throws AdscmSystemException {

        ZxdcMsgPacket packet = new ZxdcMsgPacket();


        packet.setHasResponse(false);
        packet.setLevel(3);

        ChannelHandlerContext chairCxt = ChairMgr.getInstance().getCtxByChair("chair005");

        HashMap<String, Object> values = new HashMap<String, Object>();
        packet.setValues(values);
        if ("1".equals(type)){
            packet.setCmd("startInfating");
            values.put("infating_start_time","2019-04-16 17:56:09");
            SendMsgSupport.startInfating(chairCxt,packet);
        }else if ("2".equals(type)){
            packet.setCmd("startPuncture");
            values.put("puncture_start_time","2019-04-16 17:57:19");
            SendMsgSupport.startPuncture(chairCxt,packet);
        }else if ("3".equals(type)){
            packet.setCmd("start");
//            values.put("puncture_start_time","2019-04-16 17:57:19");
            packet.setResponseFromCmd("start_collect_plasma");
            SendMsgSupport.startCollection(chairCxt);
        }



        return new SimpleCoreResponse("200", "分配成功", null);
    }

    /**
     * 接收营运模块请求的，需要发送给分配机消息的包
     * @param packet
     * @return
     * @throws AdscmSystemException
     */
    @RequestMapping("/applicationMsgToAllot")
    public SimpleCoreResponse applicationMsgToAllot(@RequestBody ZxdcMsgPacket packet) throws AdscmSystemException {

        MachineMgr.getInstance().sendMsgToAllotCtxs( packet);

        return new SimpleCoreResponse("200", "发送成功", null);
    }




}
